package com.SouthernWall_404.age_tool.Client.Sound;

import com.SouthernWall_404.age_tool.common.API.GeneralAPI;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.sounds.AbstractTickableSoundInstance;
import net.minecraft.client.resources.sounds.SoundInstance;
import net.minecraft.core.BlockPos;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.world.level.Level;

public class MusicBlockIns extends AbstractTickableSoundInstance {

    private BlockPos blockPos;
    private float defaultVolume;
    private int radius;
    private float dVolume;
    private float deltaVolume;




    public MusicBlockIns(SoundEvent soundEvent, SoundSource soundSource,float volume,float pitch, BlockPos blockPos,int radius) {
        super(soundEvent, soundSource, SoundInstance.createUnseededRandom());
        this.volume=volume;
        this.defaultVolume=volume;
        this.pitch=pitch;
        this.blockPos =blockPos;
        this.x=this.blockPos.getX();
        this.y=this.blockPos.getY();
        this.z=this.blockPos.getZ();
        //this.looping=true;
        this.delay=0;
        this.relative=false;
//        this.attenuation=Attenuation.LINEAR;
        this.radius=radius;
        this.dVolume=this.volume/this.radius;

        this.attenuation = Attenuation.NONE;
        this.looping=true;

    }

    @Override
    public void tick() {
        ticking();

    }

    private void ticking()
    {
        Level world = Minecraft.getInstance().level;
        if (world == null) {
            return;
        }//安全设置

        distanceHandler();
        particularAdd(world);
    }
    /*
    处理声音衰减的函数
    用于实现音量大小随距离的衰减效果
     */
    private void distanceHandler()
    {
        double distance= GeneralAPI.getDistanceToLocalPlayer(blockPos);

        this.deltaVolume=(float) distance*this.dVolume;

        this.volume=this.defaultVolume-this.deltaVolume;




    }
    /*
    生成粒子的函数
    用于在音乐播放时持续生成粒子
     */
    private void particularAdd(Level world)
    {
        if (world.getGameTime() % 8 == 0) {
            for (int i = 0; i < 2; i++) {
                world.addParticle(ParticleTypes.NOTE,
                        x - 0.5f + world.random.nextDouble(),
                        y + world.random.nextDouble() + 1,
                        z - 0.5f + world.random.nextDouble(),
                        world.random.nextGaussian(), world.random.nextGaussian(), world.random.nextInt(3));
            }//播放过程中的粒子效果
        }
    }
}
